package generics;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 26029
 * @date 2025/4/14
 * @description
 */
public class LearnGenerics {

    void printHello() {
        System.out.println("Hello Generics");
    }

    // 1. 方法的参数加泛型
    private static <T> void print(T content) {
        System.out.println(content);
    }

    private static void print(List<?> list) {
        for (Object object : list) {
            System.out.println(object);
        }
    }

    // 2. 方法的参数加反向，约束类型
    private static <T extends LearnGenerics> void print(T content) {
        content.printHello();
    }

    private static void printX(List<? extends Integer> list) {
        for (Object object : list) {
            System.out.println(object);
        }
    }

    // x. 甚至可以返回泛型
    private static <T> T printTReturn(T content) {
        System.out.println(content);
        return content;
    }

    public static void main(String[] args) {
        Printer<String> stringPrinter = new Printer<>("123");
        stringPrinter.print();
        Printer<Integer> integerPrinter = new Printer<>(321);
        integerPrinter.print();

        List<String> l1 = new ArrayList<>();
        List<Integer> l2 = new ArrayList<>();
        LearnGenerics.print(new LearnGenericsChild());
        LearnGenerics.print("123");
        LearnGenerics.print(l1);
        LearnGenerics.printX(l2);
        int a = LearnGenerics.printTReturn(213);
    }
}

// 3. 类的泛型
class Printer<T> {
    T content;

    Printer(T content) {
        this.content = content;
    }

    void print() {
        System.out.println(content);
    }
}

// 4.  类的指定子类型的泛型
class PrinterX<T extends LearnGenerics> {
    T content;

    PrinterX(T content) {
        this.content = content;
    }

    void print() {
        // 使用父类的printHello方法
        content.printHello();
    }
}

class LearnGenericsChild extends LearnGenerics {
    // 继承了父类的printHello方法
}
